package com.su.lightthings.utils

import android.annotation.SuppressLint
import android.content.Context
import android.net.Uri
import android.provider.ContactsContract
import android.telephony.PhoneStateListener
import android.telephony.TelephonyManager
import android.util.Log
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.su.lightthings.bluetooth.BtUtil
import com.su.lightthings.bluetooth.ProtocolDataUtil
import com.su.lightthings.viewmodel.BleViewModel
import com.su.lightthings.viewmodel.DataViewModel


class MyPhoneStateListener(val context: Context) : PhoneStateListener() {

    companion object {
        private const val TAG = "MyPhoneStateListener"
    }

    private val dataViewModel = DataViewModel.INSTANCE

    override fun onCallStateChanged(state: Int, phoneNumber: String?) {
        super.onCallStateChanged(state, phoneNumber)
        Log.d(TAG, "state: $state  >> phoneNumber: $phoneNumber ")

        if (phoneNumber?.isEmpty() == true) {
            Log.d(TAG, "phoneNumber is empty ")
            return
        }


        when (state) {
            // 当有来电时执行的操作
            TelephonyManager.CALL_STATE_RINGING -> {
                Log.d(
                    TAG,
                    "来电: $phoneNumber    >>>   is phone number null :  ${phoneNumber == null}"
                )
                if (dataViewModel.notifySwitch /*&& dataViewModel.appNotify[0].state*/) {
                    if (phoneNumber != null) {
                        val name = getContactNameByPhoneNumber(context, phoneNumber)
                        Log.d(TAG, "来电:  $name >> $phoneNumber")
                        sendToWatch(
                            TelephonyManager.CALL_STATE_RINGING,
                            name ?: phoneNumber,
                            phoneNumber
                        )
                    }
                }
            }
            // 当电话挂断时执行的操作
            TelephonyManager.CALL_STATE_IDLE -> {
                Log.d(TAG, "挂断")
                if (dataViewModel.notifySwitch /*&& dataViewModel.appNotify[0].state*/) {
                    Log.d(
                        TAG,
                        "挂断: $phoneNumber    >>>   is phone number null :  ${phoneNumber == null}"
                    )
                    if (phoneNumber != null) {
                        val name = getContactNameByPhoneNumber(context, phoneNumber)
                        Log.d(TAG, "挂断:  $name >> $phoneNumber")
                        sendToWatch(
                            TelephonyManager.CALL_STATE_IDLE,
                            name ?: phoneNumber,
                            phoneNumber
                        )
                    }
                }
            }
            // 当电话接通时执行的操作
            TelephonyManager.CALL_STATE_OFFHOOK -> {
                Log.d(TAG, "接听")
                if (dataViewModel.notifySwitch /*&& dataViewModel.appNotify[0].state*/) {
                    if (phoneNumber != null) {
                        val name = getContactNameByPhoneNumber(context, phoneNumber)
                        Log.d(TAG, "接听:  $name >> $phoneNumber")
                        sendToWatch(
                            TelephonyManager.CALL_STATE_OFFHOOK,
                            name ?: phoneNumber,
                            phoneNumber
                        )
                    }
                }
            }
        }
    }

    @SuppressLint("Range")
    fun getContactNameByPhoneNumber(context: Context, phoneNumber: String?): String? {

        if (!XXPermissions.isGranted(context, Permission.READ_CONTACTS)) {
            return null
        }

        var contactName: String? = null

        // 查询联系人数据库
        val contentResolver = context.contentResolver
        val uri = Uri.withAppendedPath(
            ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
            Uri.encode(phoneNumber)
        )
        val projection = arrayOf(ContactsContract.PhoneLookup.DISPLAY_NAME)
        val cursor = contentResolver.query(uri, projection, null, null, null)
        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    contactName =
                        cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME))
                    // 在这里你可以使用 contactName 做你需要的处理
                }
            } catch (e: Exception) {
                Log.e("ContactUtils", "Error retrieving contact name: " + e.message)
            } finally {
                cursor.close()
            }
        }
        return contactName
    }

    private fun sendToWatch(type: Int, name: String, phone: String) {
        //时间戳
        val data = ProtocolDataUtil.notifyMsgPhone(type, System.currentTimeMillis(), name, phone)
        BleViewModel.INSTANCE.write(
            BtUtil.makeWriteData(
                functionId = Cons.PushFunctionId.PUSH_MESSAGE_PHONE,
                data = data
            )
        )
    }


}